package cn.e2win.biz.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;

import cn.e2win.biz.comm.MyX509TrustManager;
import net.sf.json.JSONObject;

public class WeixinUtils {
	private static Long expiresIn=0L; //凭证有效时间
	private static JSONObject json = null;   
	private static Map<String,Object> signMap = new HashMap<String, Object>();   
	
	
	  public static Map<String, Object> getWxConfig(HttpServletRequest request) {  
	        Map<String, Object> ret = new HashMap<String, Object>();  
	        
	        String appId = PropertyPlaceholder.getProperty("weixin.APP_ID");
	        String secret = PropertyPlaceholder.getProperty("weixin.SECRET");  
	        Long now = System.currentTimeMillis();
	        String requestUrl = request.getRequestURL().toString();  
	        String access_token = "";  
	        String jsapi_ticket = "";  
	        String timestamp = Long.toString(System.currentTimeMillis() / 1000); // 必填，生成签名的时间戳  
	        String nonceStr = UUID.randomUUID().toString(); // 必填，生成签名的随机串  
	        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId + "&secret=" + secret;  
	        if(now>expiresIn){
	        	json = WeixinUtils.httpRequest(url, "GET", null);   
	        	expiresIn=now+Long.valueOf(json.getString("expires_in"))*1000;
	        }
	        if(!signMap.containsKey(requestUrl)){
	        
		        if (json != null) {  
		            access_token = json.getString("access_token");  
		            url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token + "&type=jsapi";  
		            json = WeixinUtils.httpRequest(url, "GET", null);  
		            if (json != null) {  
		                jsapi_ticket = json.getString("ticket");  
		            }  
		        }  
		        String signature = "";  
		        // 注意这里参数名必须全部小写，且必须有序  
		        String sign = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr+ "&timestamp=" + timestamp + "&url=" + requestUrl;
		        
		        try {  
		            MessageDigest crypt = MessageDigest.getInstance("SHA-1");  
		            crypt.reset();  
		            crypt.update(sign.getBytes("UTF-8"));  
		            signature = byteToHex(crypt.digest());  
		        } catch (NoSuchAlgorithmException e) {  
		            e.printStackTrace();  
		        } catch (UnsupportedEncodingException e) {  
		            e.printStackTrace();  
		        }    
	
		        System.err.println("json===" + json);
		        System.err.println("=============" + sign);
		        System.err.println("nonceStr===" + nonceStr);  
		        System.err.println("jsapi_ticket===" + jsapi_ticket);  
		        System.err.println("signature===" + signature);
		        ret.put("appId", appId);  
		        ret.put("timestamp", timestamp);  
		        ret.put("nonceStr", nonceStr);  
		        ret.put("signature", signature);  
		        signMap.put(requestUrl, ret);
	        }
	        return ret;  
	    }  
	    
	    
	    private static String byteToHex(final byte[] hash) {  
	        Formatter formatter = new Formatter();  
	        for (byte b : hash) {  
	            formatter.format("%02x", b);  
	        }  
	        String result = formatter.toString();  
	        formatter.close();  
	        return result;  
	  
	    }  
	    
	    public static JSONObject httpRequest(String requestUrl,String requestMethod, String outputStr) {  
	        JSONObject jsonObject = null;  
	        StringBuffer buffer = new StringBuffer();  
	        try {  
	            TrustManager[] tm = { new MyX509TrustManager() };  
	            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
	            sslContext.init(null, tm, new java.security.SecureRandom());  
	            SSLSocketFactory ssf = sslContext.getSocketFactory();  
	            URL url = new URL(requestUrl);  
	            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
	            httpUrlConn.setSSLSocketFactory(ssf);  
	            httpUrlConn.setDoOutput(true);  
	            httpUrlConn.setDoInput(true);  
	            httpUrlConn.setUseCaches(false);  
	            httpUrlConn.setRequestMethod(requestMethod);  
	            if ("GET".equalsIgnoreCase(requestMethod))  
	                httpUrlConn.connect();  
	            if (null != outputStr) {  
	                OutputStream outputStream = httpUrlConn.getOutputStream();  
	                outputStream.write(outputStr.getBytes("UTF-8"));  
	                outputStream.close();  
	            }  
	            InputStream inputStream = httpUrlConn.getInputStream();  
	            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
	            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
	            String str = null;  
	            while ((str = bufferedReader.readLine()) != null) {  
	                buffer.append(str);  
	            }  
	            bufferedReader.close();  
	            inputStreamReader.close();  
	            inputStream.close();  
	            inputStream = null;  
	            httpUrlConn.disconnect();  
	            jsonObject = JSONObject.fromObject(buffer.toString());  
	        } catch (ConnectException ce) {  
	            ce.printStackTrace();  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        return jsonObject;  
	    }  
	  
}
